package com.tbit.main.controller;

import cn.hutool.core.collection.CollUtil;
import com.tbit.main.common.JsonResult;
import com.tbit.main.constant.*;
import com.tbit.main.exception.BaseException;
import com.tbit.main.pojo.*;
import com.tbit.main.pojo.VO.WorkOrderCountRespVO;
import com.tbit.main.pojo.VO.WorkOrderFinishingCountRespVO;
import com.tbit.main.pojo.VO.WorkOrderFinishingQueryReqVO;
import com.tbit.main.pojo.VO.WorkOrderQueryReqVO;
import com.tbit.main.service.*;
import com.tbit.main.util.Assert;
import com.tbit.main.util.DateTimeUtil;
import com.tbit.main.util.ObjectUtil;
import com.tbit.main.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 工单
 *
 * @author LMY
 * @create 2021-05-18 15:06
 */
@RestController
@RequestMapping("/workOrder")
public class WorkOrderController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private MachineService machineService;
    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private WorkOrderFinishingService workOrderFinishingService;
    @Autowired
    private MachineOccupyService machineOccupyService;
    @Autowired
    private AccountUserService accountUserService;
    @Autowired
    private GeoreMachineService georeMachineService;
    @Autowired
    private CalibrateService calibrateService;
    @Autowired
    private PowerChangeLogService powerChangeLogService;
    @Autowired
    private MoveLogService moveLogService;
    @Autowired
    private DispatchLogService dispatchLogService;
    @Autowired
    private RepairLogService repairLogService;
    @Autowired
    private MachineManagerService machineManagerService;
    @Autowired
    private MachineFaultService machineFaultService;
    @Autowired
    private AccountUserWorkConfigService accountUserWorkConfigService;
    @Autowired
    private WorkOrderQuartzService workOrderQuartzService;
    @Autowired
    private DataService dataService;
    @Autowired
    private MachineStatusService machineStatusService;
    @Autowired
    private PowerChangeMonitorConfigService powerChangeMonitorConfigService;

    /**
     * 手工创建订单 修改工单
     */
    @RequestMapping("/build")
    public JsonResult build(String token, WorkOrder workOrder, Integer mapType) {
        Assert.notNull(workOrder.getAccountId(), "AccountUser.agentId.notNull");
        Assert.notNull(workOrder.getTitle(), "WorkOrder.title.notNull");
        Assert.notNull(workOrder.getContent(), "WorkOrder.content.notNull");
        Assert.notNull(workOrder.getWorkType(), "WorkOrder.workType.notNull");
        Assert.notNull(workOrder.getGetUserId(), "WorkOrder.getUserId.notNull");
        Assert.notNull(workOrder.getPriority(), "WorkOrder.priority.notNull");
        AccountUser accountUser = tokenService.getAccount(token);

        if (mapType == null) {
            mapType = MapConstant.MAP_GOOGLE;
        }

        if (workOrder.getUserCode() != null) {
            Machine machine = machineService.getByUseCode(workOrder.getUserCode());
            if (machine == null) {
                throw new BaseException("Machine.notExist");
            }
            /**设备权限判断*/
            machineService.auth(accountUser.getAgents(), machine.getMachineId());

            /**是否是运维占用*/
            MachineOccupy machineOccupy = machineOccupyService.getByMachineId(machine.getMachineId());
            if (machineOccupy != null) {
                throw new BaseException("WorkOrder.occupy.notOperate");
            }
            workOrder.setMachineId(machine.getMachineId());
            workOrder.setMachineNO(machine.getMachineNO());
            workOrder.setMachineType(machine.getMachineType());
            GeoreMachine georeMachine = georeMachineService.getByMachineId(machine.getMachineId());
            if (georeMachine != null) {
                workOrder.setRegionId(georeMachine.getRegionId());
            }

        }

        /**生成流水号*/
        String serNO = "";
        if (workOrder.getWorkOrderId() != null) {
            serNO = workOrder.getWorkOrderId();
        } else {
            serNO = StringUtil.getRideLogOrderNO();
        }
        workOrder.setWorkOrderId(serNO);
        workOrder.setBuildUserId(accountUser.getAccountUserId());
        workOrder.setBuildUserName(accountUser.getName());
        workOrder.setBuildType(WorkOrderConstant.buildType_H);
        workOrder.setBuildTime(DateTimeUtil.getNowTime());
        if (workOrder.getGetUserId() != null) {
            workOrder.setGetTime(DateTimeUtil.getNowTime());
            workOrder.setGetUserName(accountUser.getName());
        }
        AccountUser accountUserGet = accountUserService.getById(workOrder.getGetUserId());
        workOrder.setGetUserName(accountUserGet.getName());
        workOrder.setState(WorkOrderConstant.state_LQ);

        if (workOrder.getLat() != null) {
            Point point = new Point();
            point.setY(workOrder.getLat());
            point.setX(workOrder.getLon());
            Point pointC = calibrateService.commonCalibrate(point, mapType, SysConstant.ORIGINAL);
            workOrder.setLonC(pointC.getX());
            workOrder.setLatC(pointC.getY());
        }

        WorkOrder workOrderDB = workOrderService.getByWorkOrderId(workOrder.getWorkOrderId());
        if (workOrderDB != null) {
            if (workOrderDB.getGetUserId().equals(workOrder.getGetUserId())) {
                workOrderQuartzService.JPush(workOrder.getGetUserId(), WorkOrderConstant.buildType_H, null, WorkOrderConstant.update_Work);
            } else {
                workOrderQuartzService.JPush(workOrderDB.getGetUserId(), WorkOrderConstant.buildType_H, null, WorkOrderConstant.update_Work);
                workOrderQuartzService.JPush(workOrder.getGetUserId(), WorkOrderConstant.buildType_H, null, WorkOrderConstant.new_Work);
            }
            ObjectUtil.assign(workOrder, workOrderDB, null);
            workOrderService.update(workOrder);
            workOrderFinishingService.update(workOrder);
        } else {
            workOrderService.insert(workOrder);
            workOrderFinishingService.insert(workOrder);
            workOrderQuartzService.JPush(workOrder.getGetUserId(), WorkOrderConstant.buildType_H, null, WorkOrderConstant.new_Work);
        }

        return JsonResult.succ();
    }

    /**
     * 领取、完结工单
     */
    @RequestMapping("/finish")
    public JsonResult finish(String token, String workOrderId, Integer state) {
        Assert.notNull(workOrderId, "WorkOrder.workOrderId.notNull");
        AccountUser accountUser = tokenService.getAccount(token);
        /**领取*/
        if (state == 0) {
            WorkOrderFinishing workOrderFinishing = workOrderFinishingService.getByWorkOrderId(workOrderId);
            if (workOrderFinishing == null) {
                throw new BaseException("WorkOrder.notExist");
            } else {
                List<AccountUserWorkConfig> accountUserWorkConfigs = accountUserWorkConfigService.getAccountUserId(accountUser.getAccountUserId());
                boolean work = true;
                for (AccountUserWorkConfig accountUserWorkConfig : accountUserWorkConfigs) {
                    if (accountUserWorkConfig.getWorkType().equals(workOrderFinishing.getWorkType())) {

                        /**判断是否超过工单阈值*/
                        Integer countValue = workOrderFinishingService.getUserIdWorkType(accountUserWorkConfig.getAccountUserId(), WorkOrderConstant.workType_WX);
                        if (countValue == null || countValue < dataService.getWorkOrderConfig(workOrderFinishing.getAccountId()).getRepairNumber()) {
                            /**修改正在进行的工单表*/
                            workOrderFinishingService.updateState(workOrderId, accountUser.getAccountUserId(), accountUser.getName(), WorkOrderConstant.state_LQ);
                            /**修改工单表*/
                            workOrderService.updateState(workOrderId, accountUser.getAccountUserId(), accountUser.getName(), null, WorkOrderConstant.state_LQ, null);
                            work = false;
                            break;
                        } else {
                            throw new BaseException("WorkOrder.number.more");
                        }

                    }
                }
                if (work) {
                    throw new BaseException("WorkType.is.disaffinity");
                }

            }
        } else {
            workOrderService.updateState(workOrderId, accountUser.getAccountUserId(), accountUser.getName(), null, WorkOrderConstant.state_WC, 1);
            workOrderFinishingService.del(workOrderId);
        }
        return JsonResult.succ();
    }

    /**
     * 未完成工单类型分组
     */
    @RequestMapping("/getGroupByType")
    public JsonResult getGroupByType(String token, Integer accountId,
                                     @RequestParam(value = "regionId", required = false) List<Integer> regionId) {
        Assert.notNull(accountId, "AccountUser.agentId.notNull");
        AccountUser accountUserToken = tokenService.getAccount(token);

        List<WorkOrderTypeSta> workOrderTypeStaList = workOrderService.getGroupByType(accountId, accountUserToken, regionId);

        return JsonResult.succ(workOrderTypeStaList);
    }

    /**
     * 人员工单类型分组
     */
    @RequestMapping("/getGroupByTypeState")
    public JsonResult getByTypeState(String token, Integer accountId,
                                     @RequestParam(value = "regionId", required = false) List<Integer> regionId,
                                     String startTime, String endTime, Integer buildType, Integer workType, Integer locationType) {
        Assert.notNull(accountId, "AccountUser.agentId.notNull");
        AccountUser accountUserToken = tokenService.getAccount(token);

        List<WorkOrderSta> workOrderStaList = workOrderService.getGroupByUserId(accountId, accountUserToken.getAccountUserType(),
                accountUserToken.getAccountUserId(), startTime, endTime, workType, regionId, buildType, locationType);

        Map<Integer, List<WorkOrderSta>> map = new HashMap<>();
        for (WorkOrderSta workOrderSta : workOrderStaList) {
            if (map.containsKey(workOrderSta.getUserMainId())) {
                map.get(workOrderSta.getUserMainId()).add(workOrderSta);
            } else {
                List<WorkOrderSta> workOrderStaS = new LinkedList<>();
                workOrderStaS.add(workOrderSta);
                map.put(workOrderSta.getUserMainId(), workOrderStaS);
            }
        }

        List<WorkOrderStaReturn> workOrderStaReturnList = new LinkedList<>();

        for (Integer key : map.keySet()) {
            WorkOrderStaReturn workOrderStaReturn = new WorkOrderStaReturn();
            int count = 0;
            for (WorkOrderSta workOrderSta : map.get(key)) {
                count += workOrderSta.getWorkOrderCount();
                if (workOrderSta.getState().equals(WorkOrderConstant.state_CJ) || workOrderSta.getState().equals(WorkOrderConstant.state_LQ)) {
                    workOrderStaReturn.setNotFinishCount(workOrderSta.getWorkOrderCount());
                } else if (workOrderSta.getState().equals(WorkOrderConstant.state_SHZ)) {
                    workOrderStaReturn.setAuditorCount(workOrderSta.getWorkOrderCount());
                } else {
                    if (workOrderSta.getIsValid().equals(0)) {
                        workOrderStaReturn.setNoIsValidCount(workOrderSta.getWorkOrderCount());
                    } else {
                        workOrderStaReturn.setIsValidCount(workOrderSta.getWorkOrderCount());
                    }
                }
                workOrderStaReturn.setUserMainId(workOrderSta.getUserMainId());
                workOrderStaReturn.setName(workOrderSta.getName());
                workOrderStaReturn.setPhone(workOrderSta.getPhone());
            }
            workOrderStaReturn.setCount(count);
            workOrderStaReturnList.add(workOrderStaReturn);
        }


        return JsonResult.succ(workOrderStaReturnList);
    }

    /**
     * 未完成的工单详情
     */
    @RequestMapping("/getByFinishWork")
    public JsonResult getByFinishWork(String token, Integer accountId, @RequestParam(value = "regionId", required = false) List<Integer> regionId,
                                      Integer userMainId, Integer mapType, Integer buildType,
                                      Integer state, Integer workType, Integer machineType, Integer locationType) {

        Assert.notNull(accountId, "AccountUser.agentId.notNull");
        Assert.notNull(state, "WorkOrder.state.notNull");

        AccountUser accountUser = tokenService.getAccount(token);

        List<WorkOrderFinishing> workOrderFinishingList = workOrderFinishingService.getByUserId(accountId, accountUser, userMainId, state, workType, regionId, machineType, buildType, locationType);

        /**校准*/
        calibrateService.celibrateWorkOrderFinish(workOrderFinishingList, mapType);

        List<Integer> machineIds = workOrderFinishingList.stream().map(WorkOrderFinishing::getMachineId).collect(Collectors.toList());
        machineIds = machineIds.stream().filter(Objects::nonNull).collect(Collectors.toList());

        List<WorkOrderFinish> workOrderFinishes = new LinkedList<>();
        if (CollUtil.isNotEmpty(machineIds)) {
            Map<Integer, WorkOrderFinishing> workOrderFinishingMap = new HashMap<>();
            List<MachineStatus> machineStatusList = machineManagerService.getByMachineId(accountId, machineIds, mapType);
            Map<Integer, MachineStatus> machineStatusMap = new HashMap<>();
            for (MachineStatus machineStatus : machineStatusList) {
                machineStatusMap.put(machineStatus.getMachineId(), machineStatus);
            }

            for (WorkOrderFinishing workOrderFinishing : workOrderFinishingList) {
                workOrderFinishingMap.put(workOrderFinishing.getMachineId(), workOrderFinishing);
            }

            if (workType.equals(WorkOrderConstant.workType_WX)) {
                Map<Integer, MachineFault> machineFaultMap = new HashMap<Integer, MachineFault>();
                List<MachineFault> machineFaults;
                if (CollUtil.isEmpty(regionId)) {
                    machineFaults = machineFaultService.getByAccountId(accountId);
                } else {
                    machineFaults = machineFaultService.getByRegionId(regionId);
                }
                /*machineFaults = machineFaults.stream().filter(machineFault -> {
                    //过滤掉疑似故障
                    return !Objects.equals(machineFault.getFrom(),4);
                }).collect(Collectors.toList());*/
                for (MachineFault mf : machineFaults) {
                    machineFaultMap.put(mf.getMachineId(), mf);
                }

                for (Integer key : workOrderFinishingMap.keySet()) {
                    WorkOrderFinish workOrderFinish = new WorkOrderFinish();
                    workOrderFinish.setWorkOrderFinishing(workOrderFinishingMap.get(key));
                    workOrderFinish.setMachineFault(machineFaultMap.get(key));
                    workOrderFinish.setMachineStatus(machineStatusMap.get(key));
                    workOrderFinishes.add(workOrderFinish);
                }

            } else {
                for (Integer key : workOrderFinishingMap.keySet()) {
                    WorkOrderFinish workOrderFinish = new WorkOrderFinish();
                    workOrderFinish.setWorkOrderFinishing(workOrderFinishingMap.get(key));
                    workOrderFinish.setMachineStatus(machineStatusMap.get(key));
                    workOrderFinishes.add(workOrderFinish);
                }
            }
        } else {
            for (WorkOrderFinishing workOrderFinishing : workOrderFinishingList) {
                WorkOrderFinish workOrderFinish = new WorkOrderFinish();
                workOrderFinish.setWorkOrderFinishing(workOrderFinishing);
                workOrderFinishes.add(workOrderFinish);
            }
        }
        return JsonResult.succ(workOrderFinishes);
    }

    /**
     * 分页查询已完成工单详情
     */
    @RequestMapping("/getByTypeState")
    public JsonResult getByTypeState(String token, Integer accountId, @RequestParam(value = "regionId", required = false) List<Integer> regionId,
                                     Integer userMainId, String startTime, String endTime,
                                     Integer state, Integer workType, Integer isValid, Integer machineType, Integer buildType,
                                     Integer assign, Integer rowCount, Integer pageNO, Integer mapType, Integer locationType) {

        Assert.notNull(accountId, "AccountUser.agentId.notNull");
        AccountUser accountUserToken = tokenService.getAccount(token);


        if (rowCount == null) {
            rowCount = 10;
        }

        if (pageNO == null) {
            pageNO = 1;
        }

        if (mapType == null) {
            mapType = SysConstant.GOOGLE;
        }

        Integer count = workOrderService.getByUserIdCount(accountId, accountUserToken, userMainId, startTime,
                endTime, state, workType, isValid, regionId, assign, machineType, buildType, locationType);

        List<WorkOrderReturn> maps = new LinkedList<>();
        List<WorkOrder> workOrderList;
        if (count > 0) {
            workOrderList = workOrderService.getByUserId(accountId, accountUserToken, userMainId, startTime,
                    endTime, state, workType, isValid, regionId, assign, machineType, buildType, pageNO, rowCount, locationType);

            /**校准*/
            calibrateService.celibrateWorkOrder(workOrderList, mapType);

            if (workType != null) {
                List<Integer> businessNOList = workOrderList.stream().map(WorkOrder::getBusinessNO).collect(Collectors.toList());

                if (workType.equals(WorkOrderConstant.workType_HD)) {
                    List<PowerChangeLog> powerChangeLogs = powerChangeLogService.getPowerChangeLogIds(businessNOList);
                    Map<Integer, PowerChangeLog> powerChangeLogMap = new HashMap<>();
                    for (PowerChangeLog powerChangeLog : powerChangeLogs) {
                        powerChangeLogMap.put(powerChangeLog.getPowerChangeLogId(), powerChangeLog);
                    }

                    for (WorkOrder workOrder : workOrderList) {
                        WorkOrderReturn workOrderReturn = new WorkOrderReturn();
                        workOrderReturn.setWorkOrder(workOrder);
                        if (workOrder.getBusinessNO() != null) {
                            workOrderReturn.setPowerChangeLog(powerChangeLogMap.get(workOrder.getBusinessNO()));
                        }

                        maps.add(workOrderReturn);
                    }
                }

                if (workType.equals(WorkOrderConstant.workType_NC)) {
                    List<MoveLog> moveLogs = moveLogService.getMoveLogIds(businessNOList, mapType);
                    Map<Integer, MoveLog> moveLogMap = new HashMap<>();
                    for (MoveLog moveLog : moveLogs) {
                        moveLogMap.put(moveLog.getMoveLogId(), moveLog);
                    }

                    for (WorkOrder workOrder : workOrderList) {
                        WorkOrderReturn workOrderReturn = new WorkOrderReturn();
                        workOrderReturn.setWorkOrder(workOrder);
                        if (workOrder.getBusinessNO() != null) {
                            workOrderReturn.setMoveLog(moveLogMap.get(workOrder.getBusinessNO()));
                        }
                        maps.add(workOrderReturn);
                    }
                }

                if (workType.equals(WorkOrderConstant.workType_WX)) {
                    List<RepairLog> repairLogs = repairLogService.getRepairLogIds(businessNOList);

                    Map<Integer, RepairLog> repairLogMap = new HashMap<>();
                    for (RepairLog repairLog : repairLogs) {
                        repairLogMap.put(repairLog.getRepairLogId(), repairLog);
                    }

                    for (WorkOrder workOrder : workOrderList) {
                        WorkOrderReturn workOrderReturn = new WorkOrderReturn();
                        workOrderReturn.setWorkOrder(workOrder);
                        if (workOrder.getBusinessNO() != null) {
                            workOrderReturn.setRepairLog(repairLogMap.get(workOrder.getBusinessNO()));
                        }
                        maps.add(workOrderReturn);
                    }
                }


                if (workType.equals(WorkOrderConstant.workType_DD)) {
                    List<DispatchLog> dispatchLogs = dispatchLogService.getDispatchLogIds(businessNOList);
                    Map<Integer, DispatchLog> dispatchLogMap = new HashMap<>();
                    for (DispatchLog dispatchLog : dispatchLogs) {
                        dispatchLogMap.put(dispatchLog.getDispatchLogId(), dispatchLog);
                    }

                    for (WorkOrder workOrder : workOrderList) {
                        WorkOrderReturn workOrderReturn = new WorkOrderReturn();
                        workOrderReturn.setWorkOrder(workOrder);
                        if (workOrder.getBusinessNO() != null) {
                            workOrderReturn.setDispatchLog(dispatchLogMap.get(workOrder.getBusinessNO()));
                        }
                        maps.add(workOrderReturn);
                    }
                }
            } else {
                for (WorkOrder workOrder : workOrderList) {
                    WorkOrderReturn workOrderReturn = new WorkOrderReturn();
                    workOrderReturn.setWorkOrder(workOrder);
                    maps.add(workOrderReturn);
                }
            }
        }

        return JsonResult.succ(count, maps);
    }

    /**
     * 根据工单id查询
     */
    @RequestMapping("/getWork")
    public JsonResult getWork(String token, String workOrderId, Integer mapType) {
        WorkOrder workOrder = workOrderService.getByWorkOrderId(workOrderId);

        if (mapType == null) {
            mapType = SysConstant.GOOGLE;
        }

        calibrateService.calibrateOffSet(workOrder, mapType);
        return JsonResult.succ(workOrder);
    }

    /**
     * 删除工单
     */
    @RequestMapping("/del")
    public JsonResult del(String token, String workOrderId) {

        WorkOrderFinishing workOrderFinishing = workOrderFinishingService.getByWorkOrderId(workOrderId);

        workOrderService.del(workOrderId);
        workOrderFinishingService.del(workOrderId);

        workOrderQuartzService.JPush(workOrderFinishing.getGetUserId(), workOrderFinishing.getBuildType(), workOrderFinishing.getWorkType(), WorkOrderConstant.update_Work);

        return JsonResult.succ();
    }

    /**
     * 批量删除模糊key
     */
    @RequestMapping("/redisDel")
    public JsonResult redisDel(String token, String key) {

        if (key != null) {
            redisService.getLikeKeys(key);
        } else {
            Set<String> key1 = redisService.getLikeKeys("*" + RedisConstant.REDIS_WORK_ORDER + "*");
            redisService.delLikeKeys(key1);
            Set<String> key2 = redisService.getLikeKeys("*" + RedisConstant.REDIS_WORK_ACCOUNT + "*");
            redisService.delLikeKeys(key2);
            Set<String> key3 = redisService.getLikeKeys("*" + RedisConstant.REDIS_WORK_PUSH + "*");
            redisService.delLikeKeys(key3);
            Set<String> key4 = redisService.getLikeKeys("*" + RedisConstant.REDIS_WORK_ORDER_HD + "*");
            redisService.delLikeKeys(key4);
            Set<String> key5 = redisService.getLikeKeys("*" + RedisConstant.REDIS_WORK_ORDER_NC + "*");
            redisService.delLikeKeys(key5);
        }
        return JsonResult.succ();
    }

    /**
     * 获得根据运维人员分组的待办工单列表
     * @param reqVO 请求参数
     * @return 待办工单列表
     */
    @RequestMapping("/getWorkOrderFinishingCountGroupByAccountUser")
    public JsonResult<List<WorkOrderFinishingCountRespVO>> getWorkOrderFinishingCountGroupByAccountUser(WorkOrderFinishingQueryReqVO reqVO) {
        Assert.notNull(reqVO.getAccountId(), "AccountUser.agentId.notNull");
        // 设置人员编号
        AccountUser accountUser = tokenService.getAccount(reqVO.getToken());
        // 运维人员只能看自己
        if (accountUser.getSubRoleType().equals(2)) { // 运维人员
            reqVO.setAccountUserId(accountUser.getAccountUserId());
        }

        // 获得代办工单
        List<WorkOrderFinishing> workOrderFinishingList = workOrderFinishingService.getWorkOrderFinishingList(reqVO);

        // 根据人员分组
        Map<Integer, List<WorkOrderFinishing>> workOrderFinishingMap = workOrderFinishingList.stream()
                .filter(workOrderFinishing -> Objects.nonNull(workOrderFinishing.getGetUserId()))
                .collect(Collectors.groupingBy(WorkOrderFinishing::getGetUserId));

        // 全部工单
        WorkOrderFinishingCountRespVO workOrderFinishingCountAll = new WorkOrderFinishingCountRespVO();

        // 统计所属工种的工单数量
        LinkedList<WorkOrderFinishingCountRespVO> workOrderFinishingCountList = workOrderFinishingMap.values().stream().map(workOrderFinishings ->
            workOrderFinishingService.getWorkOrderFinishingCount(workOrderFinishingCountAll, workOrderFinishings)
        ).collect(Collectors.toCollection(LinkedList::new));

        // 运维人员不能看全部工单
        if (!accountUser.getSubRoleType().equals(2)) { // 运维人员
            workOrderFinishingCountAll.setAccountUserName("全部工单");
            workOrderFinishingCountAll.setAccountUserId(null);
            // 把全部运维添加到链表头部
            workOrderFinishingCountList.addFirst(workOrderFinishingCountAll);
        }

        return JsonResult.succ(workOrderFinishingCountList);
    }

    /**
     * 获得根据运维人员分组的已完成工单列表
     * @param reqVO 请求参数
     * @return 已完成工单列表
     */
    @RequestMapping("/getWorkOrderCountGroupByAccountUser")
    public JsonResult<List<WorkOrderCountRespVO>> getWorkOrderCountGroupByAccountUser(WorkOrderQueryReqVO reqVO) {
        Assert.notNull(reqVO.getAccountId(), "AccountUser.agentId.notNull");
        // 设置人员编号
        AccountUser accountUser = tokenService.getAccount(reqVO.getToken());
        // 运维人员只能看自己
        if (accountUser.getSubRoleType().equals(2)) { // 运维人员
            reqVO.setAccountUserId(accountUser.getAccountUserId());
        }

        // 获得完成工单
        List<WorkOrder> workOrderList = workOrderService.getWorkOrderList(reqVO);

        // 根据人员分组
        Map<Integer, List<WorkOrder>> workOrderMap = workOrderList.stream()
                .filter(workOrder -> Objects.nonNull(workOrder.getGetUserId()))
                .collect(Collectors.groupingBy(WorkOrder::getGetUserId));

        // 全部运维
        WorkOrderCountRespVO workOrderCountAll = new WorkOrderCountRespVO();

        // 统计工单数量
        LinkedList<WorkOrderCountRespVO> workOrderFinishingCountList = workOrderMap.values().stream().map(workOrders ->
            workOrderService.getWorkOrderCount(workOrderCountAll, workOrders)
        ).collect(Collectors.toCollection(LinkedList::new));

        // 运维人员不能看全部工单
        if (!accountUser.getSubRoleType().equals(2)) { // 运维人员
            workOrderCountAll.setAccountUserName("全部工单");
            workOrderCountAll.setAccountUserId(null);
            // 把全部运维添加到链表头部
            workOrderFinishingCountList.addFirst(workOrderCountAll);
        }

        return JsonResult.succ(workOrderFinishingCountList);
    }

    /**
     * 获得根据运维人员分组的待办工单列表详情
     * @param reqVO 请求参数
     * @return 待办工单列表详情
     */
    @RequestMapping("/getWorkOrderFinishingListByWorkType")
    public JsonResult<List<WorkOrderFinish>> getWorkOrderFinishingListByWorkType(WorkOrderFinishingQueryReqVO reqVO) {
        Assert.notNull(reqVO.getAccountId(), "AccountUser.agentId.notNull");
        List<WorkOrderFinishing> workOrderFinishingList = workOrderFinishingService.getWorkOrderFinishingList(reqVO);

        // 查询设备信息
        List<Integer> machineIds = workOrderFinishingList.stream().map(WorkOrderFinishing::getMachineId).collect(Collectors.toList());
        Map<Integer, MachineStatus> machineStatuses = machineStatusService.getByMachineIdBatch(machineIds)
                .stream().collect(Collectors.toMap(MachineStatus::getMachineId, Function.identity()));

        // 设备故障信息
        List<MachineFault> machineFaultList = machineFaultService.getByMachineIds(machineIds);
        /**
         * .filter(machineFault -> {
         *             //过滤掉疑似故障
         *             return !Objects.equals(machineFault.getFrom(),4);
         *         })
         * */
        Map<Integer, MachineFault> machineFaultMap = machineFaultList.stream().collect(Collectors.toMap(MachineFault::getMachineId, Function.identity()));

        // 电量和闲置时长区间
        PowerChangeMonitorConfig powerChangeMonitorConfig = powerChangeMonitorConfigService.getByAccountId(reqVO.getAccountId());

        List<WorkOrderFinish> workOrderFinishes = workOrderFinishingList.stream().map(workOrderFinishing -> {

            MachineStatus machineStatus = machineStatuses.get(workOrderFinishing.getMachineId());
            // 重置换电工单优先级
            if (workOrderFinishing.getWorkType().equals(WorkOrderConstant.workType_HD)) { // 换电工单
                Integer socPercent = machineStatus.getSocPercent();
                workOrderFinishing.setSocPercent(socPercent);

                // 车辆电量大于等于中电配置
                if (socPercent >= powerChangeMonitorConfig.getPowerMiddleMin()) {
                    workOrderFinishing.setPriority(WorkOrderConstant.priority_First); // 低优先级
                }

                // 车辆电量大于等于低电配置
                if (socPercent >= powerChangeMonitorConfig.getPowerLowMin()) {
                    workOrderFinishing.setPriority(WorkOrderConstant.priority_Second); // 中优先级
                }

                // 车辆电量等于馈电配置
                if (socPercent.equals(powerChangeMonitorConfig.getPowerFeedMax())) {
                    workOrderFinishing.setPriority(WorkOrderConstant.priority_Third); // 高优先级
                }
            }

            return new WorkOrderFinish(workOrderFinishing, machineStatus, machineFaultMap.get(workOrderFinishing.getMachineId()));
        }).collect(Collectors.toList());

        return JsonResult.succ(workOrderFinishes);
    }
}
